const { createCanvas } = require('canvas');
const express = require('express');
const fs = require('fs');
const path = require('path');
const marked = require('marked');

const app = express();

app.use(express.json());

app.post('/generate-share-image', (req, res) => {
  const { markdownContent } = req.body;

  // 使用 marked 将 Markdown 转换为 HTML
  const htmlContent = marked.parse(markdownContent);
  console.log('htmlContent--',htmlContent);

  // 设置适合小程序封面的宽高
  const width = 300;
  const height = 240;
  const canvas = createCanvas(width, height);
  const ctx = canvas.getContext('2d');

  // 设置背景颜色
  ctx.fillStyle = '#000000';
  ctx.fillRect(0, 0, width, height);

  // 设置文本样式和处理 Markdown 样式（如标题和文本）
  ctx.fillStyle = '#ffffff';
  let y = 50; 
  ctx.font = 'bold 20px Arial';
  ctx.fillText('分享封面', 50, y);
  y += 30;
  
  const processHtml = (html) => {
    const lines = html.split('\n');
    lines.forEach(line => {
      ctx.font = '16px Arial';
      ctx.fillText(line.replace(/<[^>]+>/g, ''), 50, y);
      y += 30;
    });
  };

  processHtml(htmlContent);

  // 将生成的图片保存为 PNG
  const buffer = canvas.toBuffer('image/png');
  const imagePath = path.join(__dirname, 'share-image.png');
  fs.writeFileSync(imagePath, buffer);

  // 返回生成的图片文件
  res.sendFile(imagePath);
});





app.listen(3000, () => {
  console.log('Server is running on port 3000');
});


